package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.BindTeachplanMediaDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.dto.TeachplanDto;
import com.xuecheng.commons.model.dto.TeachplanWorkDto;
import com.xuecheng.commons.model.vo.MediaVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.TeachplanVo;
import com.xuecheng.commons.model.vo.WorkVo;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.Teachplan;
import com.xuecheng.content.domain.TeachplanMedia;
import com.xuecheng.content.domain.TeachplanWork;
import com.xuecheng.content.mappers.TeachplanMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.TeachplanMediaService;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.content.service.TeachplanWorkService;
import com.xuecheng.media.api.MediaClient;
import com.xuecheng.teaching.api.TeachingClient;
import com.xuecheng.web.exceptions.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 课程计划 服务实现类
 */
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {

    @Autowired
    private CourseBaseService courseBaseService;

    /**
     * 很多种实现方式
     *
     */
    public ResponseResult<TeachplanVo> treeNodes(Long courseId) {
        //1、调用Mapper根据课程id，查询所有的课程数据  （包含1级，2级，3级）
        List<TeachplanVo> teachplanVos = null;
        teachplanVos= this.baseMapper.treeNodes(courseId);
        //teachplanVos = this.baseMapper.workTree(courseId);
        //2、筛选1级大纲
        TeachplanVo parent = teachplanVos.stream()
                .filter(vo->vo.getGrade()==1)
                .findFirst()
                .get();
        //3、筛选2级大纲，将2级大纲设置到1级中
        List<TeachplanVo> twos = teachplanVos.stream()
                .filter(vo->vo.getGrade()==2)
                .collect(Collectors.toList());
        parent.setTeachPlanTreeNodes(twos);

        //4、循环所有2级大纲，筛选2级下的三级大纲，设置到2级中
        for (TeachplanVo two: twos) {
            List<TeachplanVo> threes = teachplanVos.stream()
                    .filter(vo -> vo.getGrade() == 3 && vo.getParentid().equals(two.getId()))
                    .collect(Collectors.toList());
            two.setTeachPlanTreeNodes(threes);
        }
        return ResponseResult.okResult(parent);
    }

    //保存或者更新课程计划
    public ResponseResult saveOrUpdatePlan(TeachplanDto dto) {
        //1、判断关键信息，判断课程章节所属的课程状态
        Long courseId = dto.getCourseId();
        CourseBase base = courseBaseService.getById(courseId);
        if(base == null ||
                base.getAuditStatus().equals(CourseConstants.AUDIT_COMMIT_STATUS)||
                base.getAuditStatus().equals(CourseConstants.AUDIT_PASTED_STATUS) ||
                base.getAuditStatus().equals(CourseConstants.AUDIT_PUBLISHED_STATUS) ) {
            throw new BusinessException(ErrorCode.ERROR);
        }
        //2、处理Parentid为空的情况（保存2级大纲时），查询1级大纲的id
        if(dto.getParentid() == null) {
            LambdaQueryWrapper<Teachplan> qw = new LambdaQueryWrapper();
            qw.eq(Teachplan::getGrade,1);
            qw.eq(Teachplan::getCourseId,courseId);
            Teachplan parent = this.getOne(qw);
            dto.setParentid(parent.getId());
        }

        //3、保存或者更新
        Teachplan teachplan = BeanHelper.copyProperties(dto, Teachplan.class);
        Boolean flag = false;
        if(teachplan.getId() == null) {
            //3.1 如果id不存在，保存
            flag = this.save(teachplan);
        }else {
            //3.2 如果id存在，更新
            flag = this.updateById(teachplan);
        }

        if(!flag) {
            throw new BusinessException(ErrorCode.ERROR);
        }
        return ResponseResult.okResult();
    }

    @Autowired
    private MediaClient mediaClient;

    @Autowired
    private TeachplanMediaService teachplanMediaService;

    /**
     * 课程计划绑定媒资
     * 参数：媒资id 和 课程计划id
     */
    public ResponseResult association(BindTeachplanMediaDto dto) {
        //1、查询当前课程计划所属的课程，根据课程计划id，查询课程计划
        Teachplan teachplan = this.getById(dto.getTeachplanId());
        Long courseId = teachplan.getCourseId();
        //判断课程状态
        CourseBase courseBase = courseBaseService.getById(courseId);
        String auditStatus = courseBase.getAuditStatus();
        if (CourseConstants.AUDIT_PUBLISHED_STATUS.equals(auditStatus) ||
                CourseConstants.AUDIT_PASTED_STATUS.equals(auditStatus) ||
                CourseConstants.AUDIT_COMMIT_STATUS.equals(auditStatus)) {
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        //2、调用feign接口查询媒资
        ResponseResult<MediaVo> result = mediaClient.findById(dto.getMediaId());
        MediaVo mediaVo = result.getData();
        //3、查询当前课程计划所绑定的媒资数据
        LambdaQueryWrapper<TeachplanMedia> qw = new LambdaQueryWrapper<>();
        qw.eq(TeachplanMedia::getTeachplanId,dto.getTeachplanId());
        TeachplanMedia teachplanMedia = teachplanMediaService.getOne(qw);
        //3.1 如果不存在，保存
        Boolean flag = false;
        if(teachplanMedia == null) {
            teachplanMedia = new TeachplanMedia();
            teachplanMedia.setMediaId(dto.getMediaId());
            teachplanMedia.setMediaFilename(mediaVo.getFilename());
            teachplanMedia.setCourseId(courseId);
            teachplanMedia.setTeachplanId(dto.getTeachplanId());
            teachplanMedia.setCreateDate(new Date());
            flag =  teachplanMediaService.save(teachplanMedia);
        }else {
            //3.2 如果存在，更新
            teachplanMedia.setMediaId(dto.getMediaId());
            teachplanMedia.setMediaFilename(mediaVo.getFilename());
            flag =  teachplanMediaService.updateById(teachplanMedia);
        }
        if(!flag) {
            throw new BusinessException(ErrorCode.ERROR);
        }
        return ResponseResult.okResult();
    }

    @Autowired
    private TeachingClient teachingClient;
    @Autowired
    private TeachplanWorkService teachplanWorkService;
    //教学计划-作业绑定
    @Override
    public ResponseResult teachplanWorkAssociation(TeachplanWorkDto dto) {
//1、查询当前课程计划所属的课程，根据课程计划id，查询课程计划
        Teachplan teachplan = this.getById(dto.getTeachplanId());
        Long courseId = teachplan.getCourseId();
        //判断课程状态
        CourseBase courseBase = courseBaseService.getById(courseId);
        String auditStatus = courseBase.getAuditStatus();
        if (CourseConstants.AUDIT_PUBLISHED_STATUS.equals(auditStatus) ||
                CourseConstants.AUDIT_PASTED_STATUS.equals(auditStatus) ||
                CourseConstants.AUDIT_COMMIT_STATUS.equals(auditStatus)) {
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        //调用feign接口查询work
        ResponseResult<WorkVo> result = teachingClient.findWordById(dto.getWorkId());
        WorkVo workVo = result.getData();
        LambdaQueryWrapper<TeachplanWork> qw = new LambdaQueryWrapper<>();
        qw.eq(TeachplanWork::getTeachplanId, dto.getTeachplanId());
        TeachplanWork teachplanWork = teachplanWorkService.getOne(qw);
        //如果不存在  保存
        Boolean flag = null;
        if (teachplanWork == null) {
            teachplanWork = new TeachplanWork();
            teachplanWork.setCompanyId(AuthInfoHolder.getCompanyId());
            teachplanWork.setCourseId(courseId);
            teachplanWork.setCreateDate(new Date());
            teachplanWork.setTeachplanId(dto.getTeachplanId().longValue());
            teachplanWork.setWorkId(workVo.getWorkId().longValue());
            teachplanWork.setWorkTitle(workVo.getTitle());
            flag = teachplanWorkService.save(teachplanWork);
        } else {
            teachplanWork.setTeachplanId(dto.getTeachplanId().longValue());
            teachplanWork.setWorkId(workVo.getWorkId().longValue());
            teachplanWork.setWorkTitle(workVo.getTitle());
            flag = teachplanWorkService.updateById(teachplanWork);
        }
        if (!flag) {
            throw new BusinessException(ErrorCode.ERROR);
        }

        return ResponseResult.okResult();
    }

 /*   @Autowired
    private    TeachplanWorkService teachplanWorkService;
    //解绑作业
    @Override
    public ResponseResult<Boolean> jiebang(Long teachplanWorkId, PageRequest request) {
        Page<TeachplanWork> teachplanWorkPage = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<TeachplanWork> twQw = new LambdaQueryWrapper<>();
        twQw.eq(TeachplanWork::getId, teachplanWorkId);
        TeachplanWork teachplanWork = teachplanWorkService.getOne(twQw);
        boolean b = teachplanWorkService.removeById(teachplanWork.getId());
        return ResponseResult.okResult();
    }*/

}
